package parse.impl;

import java.util.ArrayList;
import java.util.HashMap;

import java.util.Map;

import model.ConfigModel;
import model.ReadResultModel;
import parse.ParseCore;

public class ParseToSQL implements ParseCore {

	private static ArrayList<ArrayList<String>> mainList;
	private static Map<String, ArrayList<ArrayList<String>>> subListMap;
	@SuppressWarnings("unchecked")
	private static Map<String, String> convertType = (Map<String, String>) ConfigModel.getConfig("convertType");
	private static int SUBLISTTYPE;

	@Override
	public Object doParse(ReadResultModel readResultModel, String tableName, int subListType) throws Exception {

		// 填充源文件信息
		mainList = readResultModel.getMainList();
		subListMap = readResultModel.getSubListMap();
		SUBLISTTYPE = subListType;

		// 开始构造SQL
		StringBuilder SQLResult = new StringBuilder();
		// 生成主要列表
		SQLResult.append("CREATE TABLE ").append(tableName).append("(")
				.append("`SerialNo` varchar(64) NOT NULL COMMENT '流水号',")
				.append("`QueryName` varchar(200) DEFAULT NULL COMMENT '业务主键',");
		for (int i = 1; i < mainList.size(); i++) {
			ArrayList<String> record = mainList.get(i);
			String length;
			// 替换类型关键字
			String type = record.get(4);
			// 替换中文括号为英文括号
			type.replace("（", "(");
			type.replace("）", ")");
			int indexOfLeftBracket = type.indexOf("(");
			int indexOfRightBracket = type.indexOf(")");
			String oldType;
			if (indexOfLeftBracket == -1) {
				oldType = type;
				length = "0";
			} else {
				oldType = type.substring(0, indexOfLeftBracket);
				length = type.substring(indexOfLeftBracket + 1, indexOfRightBracket);
			}
			if (convertType.containsKey(oldType.toUpperCase())) {
				record.set(4, convertType.get(oldType.toUpperCase()));
			} else {
				record.set(4, oldType);
			}
			String colName = record.get(1);
			String headChar = colName.substring(0, 1);
			colName = headChar.toUpperCase() + colName.substring(1);
			SQLResult.append("`" + colName + "` ").append("varchar(" + length + ") ").append("DEFAULT NULL COMMENT ")
					.append("'" + record.get(2) + "',");
		}
		SQLResult.append(" `EdsInputTime` varchar(20) NOT NULL COMMENT '入时间',")
				.append("`TraceId` varchar(100) NOT NULL COMMENT '业务流水号',").append("PRIMARY KEY (`SerialNo`),")
				.append("KEY `IDX_QUERYNAME` (`QueryName`),").append("KEY `IDX_EDSINPUTTIME` (`EdsInputTime`)")
				.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8 ").append("COMMENT = ;");
		// 生成次要列表
		for (int i = 1; i < mainList.size(); i++) {
			if ("JsonArray".equals(mainList.get(i).get(4))) {
				generateSubSQL(SQLResult, tableName, (mainList.get(i).get(1)));
			}
		}

		return SQLResult.toString();

	}

	private static void generateSubSQL(StringBuilder sqlResult, String tableName, String subListName) {
		if (subListMap.containsKey(subListName)) {
			ArrayList<ArrayList<String>> subList = subListMap.get(subListName);
			sqlResult.append("CREATE TABLE ").append(tableName + "_" + subListName.toLowerCase()).append("(")
					.append("`SerialNo` varchar(64) NOT NULL COMMENT '流水号',")
					.append("`QueryName` varchar(200) DEFAULT NULL COMMENT '业务主键',");
			for (int j = 1; j < subList.size(); j++) {
				ArrayList<String> subRecord = subList.get(j);
				String length;
				// 替换类型关键字
				String type = subRecord.get(2);
				// 替换中文括号为英文括号
				type.replace("（", "(");
				type.replace("）", ")");
				int indexOfLeftBracket = type.indexOf("(");
				int indexOfRightBracket = type.indexOf(")");
				String oldType;
				if (indexOfLeftBracket == -1) {
					oldType = type;
					length = "0";
				} else {
					oldType = type.substring(0, indexOfLeftBracket);
					length = type.substring(indexOfLeftBracket + 1, indexOfRightBracket);
				}
				if (1 == SUBLISTTYPE) {
					length = subRecord.get(3);
				}
				if (convertType.containsKey(oldType.toUpperCase())) {
					subRecord.set(2, convertType.get(oldType.toUpperCase()));
				} else {
					subRecord.set(2, oldType);
				}
				String colName = subRecord.get(0);
				String headChar = colName.substring(0, 1);
				colName = headChar.toUpperCase() + colName.substring(1);
				sqlResult.append("`" + colName + "` ").append("varchar(" + length + ") ")
						.append("DEFAULT NULL COMMENT ").append("'" + subRecord.get(1) + "',");
			}
			sqlResult.append(" `EdsInputTime` varchar(20) NOT NULL COMMENT '入时间',")
					.append("`TraceId` varchar(100) NOT NULL COMMENT '业务流水号',").append("PRIMARY KEY (`SerialNo`),")
					.append("KEY `IDX_QUERYNAME` (`QueryName`),").append("KEY `IDX_EDSINPUTTIME` (`EdsInputTime`)")
					.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8 ");
			HashMap<String, String> labelMap = new HashMap<>();
			for (int i = 1; i < mainList.size(); i++) {
				labelMap.put(mainList.get(i).get(1).toLowerCase(), mainList.get(i).get(2));
			}
			if (labelMap.containsKey(subListName.toLowerCase())) {
				sqlResult.append("COMMENT = " + labelMap.get(subListName.toLowerCase()) + ";");
			}
		}
	}

}
